<template>
    <div class="main">
        <!-- 优惠卷头部 -->
        <div>
            <el-space wrap :size="10">
                <el-input v-model="searchData.couponTitle" clearable placeholder="请输入优惠卷名称" />
                <el-select v-model="searchData.couponType" placeholder="请选择优惠卷类型" style="width: 10vw;" clearable
                    @clear="searchData.couponType = undefined">
                    <el-option :label="item.label" :value="item.value" v-for="item in couponType" :key="item.value" />
                </el-select>
                <el-select v-model="searchData.couponStatus" placeholder="请选择优惠卷类型" style="width: 10vw;" clearable
                    @clear="searchData.couponStatus = undefined">
                    <el-option :label="item.label" :value="item.value" v-for="item in couponStatus" :key="item.value" />
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlerSearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlerAddCoupon">添加</el-button>
                <el-button type="primary" :icon="Download" @click="deriveExcel">当前页导出</el-button>
            </el-space>
        </div>
        <div class="conten">
            <!-- 优惠卷列表 -->
            <div>
                <el-table :data="tableData" style="width: 100%" border id="table">
                    <el-table-column label="优惠卷ID" prop="id" sortable align="center" width="110" />
                    <el-table-column label="优惠卷名称" prop="title" align="center" width="110" />
                    <el-table-column label="优惠卷类型" prop="type" align="center" width="110">
                        <template #default="scope">
                            <span>{{ scope.row.type == 1 ? '满减卷' : '立减卷' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="介绍" prop="description" align="center" width="110" />
                    <el-table-column label="优惠卷数量" prop="total" align="center" width="110" />
                    <el-table-column label="剩余数量" prop="surplus" align="center" width="110" />
                    <el-table-column label="每人限额" prop="limit" align="center" width="110" />
                    <el-table-column label="满减金额" prop="discount" align="center" width="90">
                        <template #default="scope">
                            <span>减免{{ scope.row.discount }}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="最低消费" prop="min" align="center" width="90">
                        <template #default="scope">
                            <span>满{{ scope.row.min }}元可用</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="status" align="center" width="80">
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? '' : 'danger'">{{handlerProcessingStatus(scope.row.status)}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="使用类目名称" prop="categoryTitle" align="center" width="110">
                        <template #default="scope">
                            <el-tag>{{ scope.row.categoryTitle ? scope.row.categoryTitle : '全部类目' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="使用类目ID" prop="categoryId" align="center" width="110" />
                    <el-table-column label="领卷相对天数" prop="days" align="center" width="110">
                        <template #default="scope">
                            <span>{{ scope.row.days ? scope.row.days : '无' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="领卷开始时间" prop="gmtStart" align="center" width="200">
                        <template #default="scope">
                            <template v-if="scope.row.gmtStart">
                                {{ new Date(scope.row.gmtStart).formate('yyyy-MM-dd hh:mm:ss') }}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="领卷结束时间" prop="gmtEnd" align="center" width="200">
                        <template #default="scope">
                            <template v-if="scope.row.gmtEnd">
                                {{ new Date(scope.row.gmtEnd).formate('yyyy-MM-dd hh:mm:ss') }}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200">
                        <template #default="scope">
                            <el-button type="primary" v-if="scope.row.status==-1">已过期</el-button>
                            <el-button :type='scope.row.status == 0 ? "primary" : "danger"'
                                @click="handlerChangeStatus(scope.row)" v-else>{{scope.row.status==0?'激活':'冻结'}}</el-button>
                            <el-button type="info" @click="handlerSee(scope.row)">查看</el-button>
                            <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 创建对话框 -->
            <div>
                <el-dialog v-model="centerDialogVisible" :title="bool?'创建':'查看'" width="40%" align-center destroy-on-close>
                    <el-form ref="ruleFormRef" :model="form" status-icon :rules="rules" label-width="120px" :disabled="bool?false:true">
                        <el-form-item label="优惠卷名称" prop="title" class="is-required">
                            <el-input v-model="form.title" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="优惠卷类型" prop="type" class="is-required">
                            <el-select v-model="form.type" clearable placeholder="请输入优惠价类型">
                                <el-option label="满减卷" :value="1">满减卷</el-option>
                                <el-option label="立减卷" :value="2">立减卷</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="介绍" prop="description" class="is-required">
                            <el-input v-model="form.description" />
                        </el-form-item>
                        <el-form-item label="优惠卷数量" prop="total" class="is-required">
                            <el-input v-model.number="form.total">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="每人限领" prop="limit" class="is-required">
                            <el-input v-model.number="form.limit">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠金额" prop="discount" class="is-required">
                            <el-input v-model.number="form.discount">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="最低消费" prop="min" class="is-required">
                            <el-input v-model.number="form.min">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="优惠卷状态" prop="status" class="is-required">
                            <el-select v-model="form.status" clearable placeholder="请输入用户等级">
                                <el-option label="下架" :value="0">下架</el-option>
                                <el-option label="正常" :value="1">正常</el-option>
                                <el-option label="已过期" :value="-1">已过期</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="有效期">
                            <el-radio-group v-model="expiration" @change="change">
                                <el-radio-button :label="0">领卷相对天数</el-radio-button>
                                <el-radio-button :label="1">指定绝对时间</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="expiration == 0">
                            <el-input v-model.number="form.days">
                                <template #append>天</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item v-else prop="gmtEnd">
                            <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="开始时间"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                            <span>至</span>
                            <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="结束时间"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" />
                        </el-form-item>
                        <el-form-item label="商品限制范围">
                            <el-radio-group v-model="limitedField" @change="categoryChange">
                                <el-radio-button :label="0">全场通用</el-radio-button>
                                <el-radio-button :label="1">指定分类</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="优惠类目" v-if="limitedField == 1">
                            <el-cascader v-model="form.categoryId" :options="options" :props="props" clearable />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="centerDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="bool">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main"  :visibility-height="20" />
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { ClassPagination } from "#/index";
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox} from 'element-plus'
import deriveExcel from '@/utils/export'
import Paging from "@/components/paging/Paging.vue";
import { post } from "@/utils/http";
import type { FormInstance } from 'element-plus'
import '@/utils/dataFriend'
const ruleFormRef = ref<FormInstance>()
const tableData: TypeCoupon[] = reactive([])
//请求分页的数据
let pagingDatas = reactive(new ClassPagination)
const centerDialogVisible = ref(false) //控制弹出框是否可见
const main = ref()  //滚动组件对象的引用
const searchData = reactive({
    couponTitle: '', //优惠卷名称
    couponType: undefined,//优惠卷类型
    couponStatus: undefined,//优惠卷状态
})
const props = {
    emitPath: false,
    checkStrictly: true,
    value: 'id',
    label: 'title',
    children: 'childrenList'
}
let bool = ref(true)
const options: TypeCategory[] = reactive([])
let newSearchData = reactive({ ...searchData })
const expiration = ref(0) //用来判断是天数还是时间
const limitedField = ref(0) //用来判断是全场通用还是别的
const couponType = ref([
    {
        'label': '满减卷',
        'value': 1
    },
    {
        'label': '立减卷',
        'value': 2
    },
    {
        'label': '全部',
        'value': ''
    }
])
const couponStatus = ref([
    {
        'label': '下架',
        'value': 0
    },
    {
        'label': '正常',
        'value': 1
    },
    {
        'label': '已过期',
        'value': -1
    },
    {
        'label': '全部',
        'value': ''
    }
])
//添加弹出框绑定数据
const form = reactive({
    title: '', //优惠卷名称
    type: '', //优惠卷类型
    description: '', //介绍
    total: 0, //优惠卷数量
    limit: 0, //每人限领
    discount: 0, //优惠金额
    min: 0, //最低消费
    status: 1,//优惠卷状态
    days: '', //相对天数
    gmtStart: '',//开始时间
    gmtEnd: '', //结束时间
    categoryId: '' //优惠类目
})
const newForm = reactive({...form})
//  优惠卷名称和介绍验证
const validateTitle = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入内容'))
    }
    callback()
}
//优惠卷数量验证
const validateTotal = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value == '' || value == 0) {
        callback(new Error('数量必须大于0'))
    } else if (!regexp.test(value)) {
        callback(new Error("数量必须是数字"))
    } else if (value < form.limit) {
        callback(new Error("优惠卷数量必须大于每人限领"))
    }
    callback()
}

//每人限领验证
const validateLimit = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value == '' || value == 0) {
        callback(new Error('数量必须大于0'))
    } else if (!regexp.test(value)) {
        callback(new Error("数量必须是数字"))
    } else if (value > form.total) {
        callback(new Error("每人限领不能大于优惠卷数量"))
    }
    callback()
}
//切换类目事件
const categoryChange = (e:number)=>{
    if(e==0){
        form.categoryId = ''
    }
}
//切换单选按钮事件
const change = (e: number) => {
    if (e == 0) {
        form.gmtStart = ''
        form.gmtEnd = ''
    } else {
        form.days = ''
    }
}

//优惠金额验证
const validateDiscount = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value == '' || value == 0) {
        callback(new Error('数量必须大于0'))
    } else if (!regexp.test(value)) {
        callback(new Error("数量必须是数字"))
    } else if (form.min < value) {
        console.log(11111);
        callback(new Error("优惠金额必须大于最低消费"))
    }
    callback()
}
//最低消费验证
const validateMin = (rule: any, value: any, callback: any) => {
    var regexp = /^\d{1,}$/
    if (value == '' || value == 0) {
        callback(new Error('数量必须大于0'))
    } else if (!regexp.test(value)) {
        callback(new Error("数量必须是数字"))
    } else if (value < form.discount) {
        callback(new Error("最低消费要大于优惠金额"))
    }
    callback()
}
//结束时间验证
const validateGmtEnd = (rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入结束时间'))
    } else if (value < form.gmtStart) {
        callback(new Error("结束时间必须大于开始时间"))
    }
    callback()
}
//验证规则
const rules = reactive({
    title: [{ validator: validateTitle, trigger: 'blur' }],
    type: [{ validator: validateTitle, trigger: 'change' }],
    description: [{ validator: validateTitle, trigger: 'blur' }],
    total: [{ validator: validateTotal, trigger: 'blur' }],
    limit: [{ validator: validateLimit, trigger: 'blur' }],
    discount: [{ validator: validateDiscount, trigger: 'blur' }],
    min: [{ validator: validateMin, trigger: 'blur' }],
    gmtEnd: [{ validator: validateGmtEnd, trigger: 'change' }]
})
//优惠卷列表
const loadCouponList = () => {
    let data = {
        _gp: 'admin.coupon',
        _mt: 'list',
        title: newSearchData.couponTitle,
        type: newSearchData.couponType,
        status: newSearchData.couponStatus,
        pageNo: pagingDatas.page,
        limit: pagingDatas.limit
    }
    post(data).then(res => {
        console.log(res);
        let {errno,data,errmsg} = res
        if (200 == errno) {
            data.items.forEach((item:TypeCoupon)=>{
                if(item.gmtEnd&&item.gmtEnd< +new Date()){
                    item.status = -1
                }
            })
            tableData.length = 0
            pagingDatas.total = res.data.total
            tableData.push(...res.data.items)
        } else {
            ElMessage.error(errmsg)
        }
    })
}

loadCouponList()
//处理状态
const handlerProcessingStatus = (status:number)=>{
    if(status==0){
        return '下架'
    }else if(status==1){
        return '正常'
    }else if(status<0){
        return '已过期'
    }
}

//类目列表
const lodeCategory = () => {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    if (options.length == 0) {
        post(data).then(res => {
            console.log(res);
            if (200 == res.errno) {
                options.length = 0
                options.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCategory()
//查找
const handlerSearch = () => {
    Object.assign(newSearchData, searchData)
    pagingDatas.page = 1
    loadCouponList()
}
//查看
const handlerSee = (row:TypeCoupon)=>{
    console.log(row);
    bool.value = false
    Object.assign(form,newForm)
    Object.assign(form,row)
    expiration.value = row.gmtStart?1:0
    limitedField.value = row.categoryTitle ? 1:0
    // if(row.gmtEnd<new Date().getTime()){
    //     form.status = -1
    // }
    centerDialogVisible.value = true
}

//添加
const handlerAddCoupon = () => {
    centerDialogVisible.value = true
    Object.assign(form,newForm)
    expiration.value = 0
    limitedField.value = 0
    bool.value = true
}

const handleDelete = (index:number,row:TypeCoupon)=>{
    let data = {
        _gp: "admin.coupon",
        _mt: 'delete',
        id: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            post(data).then(res => {
                if (200 == res.errno) {
                    ElMessage.success('删除成功')
                    loadCouponList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })

        })
        .catch(() => {
            ElMessage.info('取消操作')
        })
}

//添加确定
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
             let data = {
                _gp:'admin.coupon',
                _mt:'create',
                ...form
             }
             post(data).then(res=>{
                console.log(res);
                if(200==res.errno){
                    centerDialogVisible.value = false
                    ElMessage.success('添加成功')
                    loadCouponList()
                }else{
                    ElMessage.error(res.errmsg)
                }
             })
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}
//修改状态
const handlerChangeStatus = (row: TypeCoupon) => {
    let data = {
        _gp: 'admin.coupon',
        _mt: 'updateCouponStatus',
        id: row.id,
        status: row.status == 0 ? 1 : 0
    }
    post(data).then(res => {
        if (200 == res.errno) {
            ElMessage.success("修改成功")
            loadCouponList()
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}
//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadCouponList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}



</script>
<style lang="less" scoped>
.main {
    >div {
        margin: 15px 0px;

        .el-input {
            width: 11vw;
        }
    }

    .conten {
        .el-dialog {
            .el-form {
                .el-form-item__content {
                    .el-input {
                        width: 28vw;
                    }
                }
            }
        }
    }
}
</style>